/*
 * Author: 李波(Edwin Lee)
 * Date: 2024-08-20 15:00:48
 * FilePath: /mprpc/src/include/lockqueue.hpp
 * LastEditTime: 2024-08-26 07:10:07
 * version: 1.0
 * Description: 封装了锁的队列模板（用于异步日志缓存日志信息）
 */

#ifndef __LOCKQUEUE_H__
#define __LOCKQUEUE_H__

#include <mutex>
#include <queue>
#include <condition_variable>

template<typename T>
class LockQueue
{
public:
    //description: 多个worker线程都会写日志queue
    //param data:
    //return {void}
    //Date: 2024-08-22 08:31:32
    void push(const T& data)
    {
        std::lock_guard<std::mutex> lock(mutex_);
        queue_.push(data);
        cond_.notify_one();
    }

    //description: 一个线程读日志queue，写日志文件
    //Date: 2024-08-22 10:41:46
    T pop()
    {
        std::unique_lock<std::mutex> lock(mutex_);
        while(queue_.empty())
        {
            cond_.wait(lock);
        }
        T data = queue_.front();
        queue_.pop();
        return data;
    }
private:
    std::queue<T> queue_;
    std::mutex mutex_;
    std::condition_variable cond_;
};

#endif